package cn.tedu.carehome.foundation.timer;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.http.HttpUtil;
import cn.tedu.carehome.foundation.mapper.VisitorMapper;
import cn.tedu.carehome.foundation.pojo.entity.Visitor;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class Testkeliu {

    @Autowired
    private VisitorMapper visitorMapper;

    public static final String APPID = "d4a70d16723543829b0fffc2fe0fff62";// 从开发者得到
    public static final String CPID = "1556144723491524610";// 从开发者得到
    public static final String SECRET = "5e60b374-b648-46d5-b356-791f18d75bed"; // 从开发者得到
    public static final Map<String, String> tokenMap = new HashMap<>();

    public void main() throws SQLException {
        String token = getToken(APPID, CPID, SECRET);
        getEntityData(token);
//        Testkeliu.getPassagewayData(token);
    }

    public boolean isNotEmpty(String str) {
        return str != null && !str.isEmpty();
    }

    public String getToken(String appId, String cpid, String secret) {
        // 此处模拟存在redis中,设置过期策略, 请不要直接这么使用
        String cacheToken = tokenMap.get(appId);
        if (isNotEmpty(cacheToken)) {
            return cacheToken;
        }
        Long createTime = System.currentTimeMillis();
        Map<String, String> params = new HashMap<>();
        params.put("appId", appId);
        params.put("cpid", cpid);
        params.put("createTime", createTime.toString());
        //cn.hutool.core.map public class MapUtil
        // 参数需要进行排序再连接
        String original = MapUtil.sortJoin(params, "&", "=", true) + "&" + secret;
        // cn.hutool.crypto.digest.Digester
        Digester MD5 = new Digester(DigestAlgorithm.MD5);
        String sign = MD5.digestHex(original, StandardCharsets.UTF_8);

        String requestParams = MapUtil.sortJoin(params, "&", "=", true) + "&sign=" + sign;

        String res = HttpUtil.post("http://kl.klyun168.com/klyun/auth/openapi/v1/token", requestParams);
        log.info("res={}", res);
        if (isNotEmpty(res)) {
            JSONObject jsonObject = JSON.parseObject(res);
            Integer code = jsonObject.getInteger("code");
            if (code == 200) {
                JSONObject data = jsonObject.getJSONObject("data");
                String accessToken = data.getString("accessToken");
                // 模拟存在redis中
                tokenMap.put(appId, accessToken);
                return accessToken;
            }
        }
        return null;
    }

    public List<Object> objectToList(Object object) {
        List<Object> list = new ArrayList<>();
        if (object instanceof Object[]) {
            list.addAll(Arrays.asList((Object[]) object));
        } else if (object instanceof Collection) {
            list.addAll((Collection<?>) object);
        } else {
            list.add(object);
        }
        return list;
    }

    public void getEntityData(String accessToken) throws SQLException {
        HashMap<String, String> params = new HashMap<>();
        params.put("dimension", "hour");
        params.put("openId", "704279fde79a459a9ec287a4f5f4c0e9");
        Date currentDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = dateFormat.format(currentDate);
//        System.out.println(formattedDate);

        params.put("startDate", formattedDate);
        params.put("endDate", formattedDate);
        String requestParams = getRequestParams(APPID, accessToken, SECRET, params);
        String res = HttpUtil.post("http://kl.klyun168.com/klyun/kl/openapi/v1/entity/data", requestParams);
        log.info("得到数据={}", res);
        if (isNotEmpty(res)) {
            JSONObject jsonObject = JSON.parseObject(res);
            List<Object> oc = objectToList(jsonObject.get("data"));
            for (int i = 0; i < oc.size(); i++) {
                Visitor visitor = new Visitor();
                visitor.setStartDate(((JSONObject) oc.get(i)).getString("startDate"));
                visitor.setEndDate(((JSONObject) oc.get(i)).getString("endDate"));
                visitor.setEntersNumber(((JSONObject) oc.get(i)).getString("entersNumber"));
                visitor.setExitsNumber(((JSONObject) oc.get(i)).getString("exitsNumber"));
                visitor.setPassingsNumber(((JSONObject) oc.get(i)).getString("passingsNumber"));
                visitor.setReturnNumber(((JSONObject) oc.get(i)).getString("returnNumber"));
                visitor.setStrandNumber(((JSONObject) oc.get(i)).getString("strandNumber"));
                visitor.setDataDate(((JSONObject) oc.get(i)).getString("dataDate"));
//            visitorMapper.deleteBYdataDate();
                Db.use().execute("delete from visitor where dataDate = ?",  visitor.getDataDate());
                Db.use().insert(
                        Entity.create("visitor")
                                .set("startDate", visitor.getStartDate())
                                .set("endDate", visitor.getEndDate())
                                .set("entersNumber", visitor.getEntersNumber())
                                .set("exitsNumber", visitor.getExitsNumber())
                                .set("passingsNumber", visitor.getPassingsNumber())
                                .set("returnNumber", visitor.getReturnNumber())
                                .set("strandNumber", visitor.getStrandNumber())
                                .set("dataDate", visitor.getDataDate())
                );
            }
        }
    }

    public void getPassagewayData(String accessToken) {
        HashMap<String, String> params = new HashMap<>();
        params.put("dimension", "five");
        params.put("openId", "704279fde79a459a9ec287a4f5f4c0e9");
        params.put("startDate", "2024-09-01");
        params.put("endDate", "2024-09-01");
        String requestParams = getRequestParams(APPID, accessToken, SECRET, params);
        String res = HttpUtil.post("http://kl.klyun168.com/klyun/kl/openapi/v1/passageway/data", requestParams);
        log.info("得到数据={}", res);
        if (isNotEmpty(res)) {
            JSONObject jsonObject = JSON.parseObject(res);
        }
    }

    public String getRequestParams(String appId, String accessToken, String secret, Map<String, String> params) {
        Long createTime = System.currentTimeMillis();
        params.put("appId", appId);
        params.put("accessToken", accessToken);
        params.put("createTime", createTime.toString());
        //cn.hutool.core.map public class MapUtil
        String original = MapUtil.sortJoin(params, "&", "=", true) + "&" + secret;
        // cn.hutool.crypto.digest.Digester
        Digester MD5 = new Digester(DigestAlgorithm.MD5);
        String sign = MD5.digestHex(original, StandardCharsets.UTF_8);
        String requestParams = MapUtil.sortJoin(params, "&", "=", true) + "&sign=" + sign;
        return requestParams;
    }

}